package com.guoliang.wechatpushing.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.guoliang.wechatpushing.constant.Constant;
import com.guoliang.wechatpushing.service.AphorismService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.io.IOException;
import java.util.List;
import java.util.Random;

/**
 * @author ：Leo
 * @date ：Created in 2022/10/18 16:33
 * @description：
 */
@Service
@Slf4j
public class AphorismServiceImpl implements AphorismService {
    @Autowired
    Constant constant;
    @Override
    public String getAphorism() throws IOException {
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        Integer titleId= new Random().nextInt(9);
        RequestBody body = RequestBody.create(mediaType,"titleID="+titleId.toString());
        Request request = new Request.Builder()
                .url("https://eolink.o.apispace.com/myjj/common/aphorism/getAphorismList")
                .method("POST",body)
                .addHeader("X-APISpace-Token",constant.token)
                .addHeader("Authorization-Type","apikey")
                .addHeader("Content-Type","")
                .build();
        Response response = client.newCall(request).execute();
        JSONObject jsonObject = JSONObject.parseObject(response.body().string());
        JSONArray result = jsonObject.getJSONArray("result");
        if (result==null) {
            log.info("名言获取失败");
            return "萤火虫的光点虽然微弱，但亮着便是向黑暗挑战。";
        };
        String words = (String)((JSONObject) result.get(0)).get("words");
        List<String> list = JSONObject.parseArray(words, String.class);//将json字符串转化为集合对象
        String s= list.get(new Random().nextInt(list.size()));
        while (s.length()>35) s= list.get(new Random().nextInt(list.size()));
        s=s.substring(s.indexOf("、")+1);
        s.replace("；","，");
        return s;
    }
}
